#include "HttpServer.hpp"
#include <time.h>
std::string GetDayOfWeek(int n)
{
    std::vector<std::string> v = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    return v[n];
}
std::string GetMonthName(int month)
{
    std::vector<std::string> months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    return months[month];
}
// t 秒后过期
std::string GetExpireTime(int t)
{
    time_t curtime = time(nullptr)+t;
    struct tm *tm = gmtime(&curtime);
    char timebuffer[1024];
    // expires=Wed, 09 Jun 2023 10:18:14 GMT;
    snprintf(timebuffer,sizeof(timebuffer),"%s, %02d %s %d %02d:%02d:%02d UTC",GetDayOfWeek(tm->tm_wday).c_str(),tm->tm_mday,GetMonthName(tm->tm_mon).c_str(),tm->tm_year+1900,
    tm->tm_hour,tm->tm_min,tm->tm_sec);
    return timebuffer;  
}
HttpResponse Login(HttpRequest &request)
{

    LOG(LogLevel::DEBUG) << "根据参数，进行一系列处理";
    // 1.参数的格式解析
    // 2.访问数据库，验证用户是否存在，等其他操作
    // 前两步不做了
    // 3.登录成功
    HttpResponse res;
    std::string content;
    res.GetContent("wwwroot/loginsuccess.html", &content);
    res.SetBody(content);
    res.SetCode(200);
    // res.AddHeader("Set-Cookie",request.Args());
    // Set-Cookie: sessionId=abc123def456; expires=Wed, 09 Jun 2023 10:18:14 GMT; domain=example.com; path=/; secure; HttpOnly; SameSite=Lax
    // path是请求该路径下的资源时才会在请求行中带Cookie
    // res.AddHeader("Set-Cookie","username=wmz; path=/a/b");
    // std::string cookie = "username=wmz; path=/; ";
    // cookie+="expires="+GetExpireTime(60);//设置过期时间1 min
    // res.AddHeader("Set-Cookie",cookie);
    std::string cookie = "sessionid=";
    cookie+=request.SessionId();
    res.AddHeader("Set-Cookie",cookie);
    return res;
}
int main()
{
    std::unique_ptr<HttpServer> httpserver(new HttpServer());
    httpserver->Register("/login", [](HttpRequest &request) -> HttpResponse
                         { return Login(request); });
    httpserver->Start();
    return 0;
}